package com.gk.panda.apis.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gk.panda.apis.Vo.UserOrgVo;
import com.gk.panda.apis.dto.*;
import com.gk.panda.apis.log.Log;
import com.gk.panda.apis.service.OrgService;
import com.gk.panda.apis.service.UserService;
import com.gk.panda.commons.result.Result;
import com.gk.panda.pojo.Org;
import com.gk.panda.pojo.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * 用户管理控制器
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserController {

    private static final String DEFAULT_PASSWORD = "Park@123456";

    @Autowired
    private UserService userService;

    @Autowired
    private OrgService orgService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @ApiOperation(value = "查询用户")
    @PostMapping("/page")
    public Result<Page<User>> searchUsers(@RequestBody UserSearchDto searchDto){
        return Result.ok(userService.searchUsers(searchDto));
    }

    @ApiOperation(value = "添加用户")
    @Log
    @PostMapping
    public Result<String> addUser(@RequestBody User user){

        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("phone",user.getPhone()).or().eq("username",user.getUsername());
        User dbUser = userService.getOne(wrapper);
        if (dbUser != null) return Result.write(201,"用户名或手机号已存在");
        user.setPassword(passwordEncoder.encode(DEFAULT_PASSWORD));
        Org org = orgService.getById(user.getOrgId());
        user.setAvatar("http://118.121.196.46:8000/group1/M00/00/98/dnnELmN0N0uAS4_6AABcfCofN5A170.png");
        user.setOrgName(org.getName());
        boolean save = userService.save(user);
        if (!save) return Result.write(201,"添加失败");
        return Result.write(200,"添加成功");
    }

    @ApiOperation(value = "修改用户")
    @Log
    @PutMapping
    public Result<String> updateUser(@RequestBody UserUpdateDto updateDto) {
        int update = userService.updateUser(updateDto);
         if (update == 1) {
            return Result.write(200,"修改成功");
        }
         return Result.write(201,"修改失败");
    }

    @ApiOperation(value = "重置密码")
    @Log
    @PutMapping("/resetPassword")
    public Result<String> resetPassword(String username) {
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.set("password",passwordEncoder.encode(DEFAULT_PASSWORD));
        wrapper.eq("username",username);
        boolean update = userService.update(wrapper);
        if (update) return Result.write(200,"重置密码成功");
        return Result.write(201,"重置密码失败");
    }

    @ApiOperation(value = "用户修改个人资料")
    @Log
    @PutMapping("/personalData")
    public Result<String> updatePersonalData(@RequestBody PersonalDataDto dataDto) {
        int update = userService.updatePersonalData(dataDto);
        if (update == -1) {
            return Result.write(201,"不能修改他人信息");
        } else if (update == 1) {
            return Result.write(200,"修改成功");
        } else return Result.write(201,"修改失败");
    }

    @ApiOperation(value = "用户修改个人密码")
    @Log
    @PutMapping("/personalPassword")
    public Result<String> updatePersonalPassword(@RequestBody PasswordDto dto) {
        int update = userService.updatePersonalPassword(dto);
        if (update == -1) {
            return Result.write(201,"原密码错误");
        } else if (update == 0) {
            return Result.write(201,"修改失败");
        } else return Result.write(200,"修改成功");

    }

    @ApiOperation(value = "用户获取个人信息")
    @GetMapping("/userInfo")
    public Result<User> getUserInfo() {
        return Result.ok(userService.getUserInfo());
    }

    @ApiOperation(value = "启用/禁用用户")
    @Log
    @PutMapping("/state")
    public Result<String> updateUserState(@RequestBody UserStatusDto statusDto){
        UpdateWrapper<User> wrapper =new UpdateWrapper<>();
        wrapper.set("status", statusDto.getStatus());
        wrapper.eq("username", statusDto.getUsername());
        boolean update = userService.update(wrapper);
        if (update) return Result.write(200,"修改状态成功");
        return Result.write(201,"修改状态失败");
    }

    @ApiOperation(value = "删除用户")
    @Log
    @DeleteMapping("/{username}")
    public Result<Integer> deleteUser(@PathVariable String username){
        boolean remove = userService.removeById(username);
        if (remove) return Result.write(200,"删除成功");
        return Result.write(201,"删除失败");
    }

    @ApiOperation(value = "获取用户分站总站信息")
    @PostMapping("/getOrgInfo")
    public Result<UserOrgVo> getOrgInfo(@RequestBody User user){
        //查询用户
        User dbUser = userService.getById(user.getUsername());
        if(ObjectUtils.isEmpty(dbUser))return Result.write(201,"该用户不存在");
        //查询机构
        Org org = orgService.getById(dbUser.getOrgId());

        UserOrgVo userOrgVo = new UserOrgVo();
        userOrgVo.setUsername(user.getUsername());
        if(!ObjectUtils.isEmpty(org)){
            if(!StringUtils.isEmpty(org.getType())){
                if("0".equals(org.getType())){
                    //用户所属最高级
                    userOrgVo.setAbbr(org.getAbbr());
                }else if("1".equals(org.getType())){
                    //自己所属总站
                    userOrgVo.setAbbr(org.getAbbr());
                    userOrgVo.setTotleOrg(org.getName());
                    userOrgVo.setTotleOrgId(org.getId());
                    System.out.println();
                }else{
                    //用户所属为分站
                    Org totleOrg = orgService.getById(org.getParentId());
                    userOrgVo.setAbbr(totleOrg.getAbbr());
                    userOrgVo.setTotleOrg(totleOrg.getName());
                    userOrgVo.setTotleOrgId(totleOrg.getId());
                    userOrgVo.setBranchOrg(org.getName());
                    userOrgVo.setBranchOrgId(org.getId());
                }
            }
        }
        return Result.ok(userOrgVo);
    }
}
